<template>
  <a-modal
    :title="title"
    :maskClosable="false"
    :width="900"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <div>
      <a-row>
        <a-col>
          <div class="mb10">已选机台：{{ chose.length }}台</div>
          <!--          <div class="tag-list">-->
          <!--            <a-tag-->
          <!--              v-for="(tag, i) in tags"-->
          <!--              :key="i"-->
          <!--              size="small"-->
          <!--              color="blue"-->
          <!--            >-->
          <!--              {{ tag }}-->
          <!--              <span style="cursor: pointer;font-size: 15px;" @click="closeTag(tag, i)">×</span>-->
          <!--            </a-tag>-->
          <!--          </div>-->
        </a-col>
      </a-row>
      <div class="box mb10">
        <div class="content">
          <template>
            <my-checkbox-group v-model:value="chose" style="width: 100%" @change="toggleChose" :enable-drag="true">
              <div class="equipment-scope" v-for="(row, index) in showList" :key="index">
                <div class="title-cj">{{ row.productTypeTxt }}</div>
                <div style="">
                  <div v-for="(item, i) in row.equipList" :key="i" style="">
                    <a-space>
                      <div class="title-cj">{{ item.cj }}</div>
                      <a-space style="margin-left: 20px;">
                        <a-input
                          v-model:value="item.startNum"
                          style="width: 100px;"
                          size="small"
                          placeholder="请输入"
                        />
                        <span>~</span>
                        <a-input v-model:value="item.endNum" size="small" style="width: 100px;" placeholder="请输入" />
                        <a-button type="primary" size="small" @click="checkBtn(item)">选择</a-button>
                        <a-button size="small" @click="unCheckBtn(item)">取消</a-button>
                      </a-space>
                    </a-space>
                    <div style="margin-top: 10px;display:flex;flex-wrap: wrap;">
                      <div v-for="(itemDevSnArea, i) in item.devSnArea" :key="i" style="width: 60px;">
                        <my-checkbox-button :value="row.id + '*' + itemDevSnArea.id" :key="i">
                          <!--                        {{ itemDevSnArea.workshopDictText + '#' + itemDevSnArea.deviceNo }}-->
                          {{ itemDevSnArea.deviceNo }}
                        </my-checkbox-button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </my-checkbox-group>
          </template>
        </div>
      </div>
    </div>
  </a-modal>
</template>

<script>
import MyCheckboxGroup from '@/components/myCheckbox/MyCheckboxGroup.vue'
import MyCheckboxButton from '@/components/myCheckbox/MyCheckboxButton.vue'
import { httpAction } from '@/api/manage'
import { getDevice } from '@/api/customApi'
import JEditor from '@/components/jeecg/JEditor'
import JSwitch from '@/components/jeecg/JSwitch'
import { editDevice, getDailyPlanPreSpin } from '../../../../api/customApi'
import moment from 'moment'

export default {
  props: {
    planTimeJiTai: String,
    workshopJiTai: String
  },
  name: 'JitaiModal',
  components: {
    JEditor,
    JSwitch,
    MyCheckboxGroup,
    MyCheckboxButton
  },
  data() {
    return {
      title: '选择机台',
      isEquipment: false,
      addTable: true,
      visible: false,
      rowId: '', //排班ID
      planId: null, //日计划ID
      row: {},
      editItem: {},
      model: {},
      confirmLoading: false,
      selectDeviceIds: [],
      device: [],
      chose: [],
      tags: [],
      equipList: [],
      showList: [],
      selectPlanData: [],
      process: '',
      url: {
        add: '/crm_daily_plan_pre_spin/crmDailyPlanPreSpin/add',
        edit: '/crm_daily_plan_pre_spin/crmDailyPlanPreSpin/edit'
      }
    }
  },
  created() {},
  methods: {
    show(records, param, isAddTable, changeEdit = false) {
      this.showList = []
      this.changeEdit = changeEdit
      this.visible = true
      this.addTable = isAddTable
      if (param == '清花') {
        this.process = '1'
      }
      if (param == '梳棉') {
        this.process = '2'
      }
      if (param == '精梳') {
        this.process = '3'
      }
      if (param == '并条') {
        this.process = '4'
      }
      if (param == '粗纱') {
        this.process = '5'
      }
      if (param == '细纱') {
        this.process = '6'
      }
      if (param == '络筒') {
        this.process = '7'
      }
      const originalData = []
      if (isAddTable) {
        this.row = records
      } else {
        this.row = records.schedulingPreSpinDevices
        this.rowId = records.id
        this.planId = records.planId
        this.editItem = records
      }

      if (this.row) {
        this.row.forEach(item => {
          const dailyPlanId = item.dailyPlanId
          const deviceIdsArray = item.deviceIds.split(',').map(id => id.trim())

          deviceIdsArray.forEach(deviceId => {
            originalData.push(`${dailyPlanId}*${deviceId}`)
          })
        })

        console.log(originalData)

        this.chose = originalData
      }

      this.$nextTick(() => {
        this.getDevSn()
      })
    },
    getDevSn() {
      let query = {
        planTime: this.planTimeJiTai,
        workshop: this.workshopJiTai,
        id: this.planId,
        workingProcedure: this.process,
        column: 'company,workshop,workingProcedure',
        order: 'asc,asc,asc'
      }
      getDailyPlanPreSpin(query).then(res => {
        this.showList = []
        if (res.success) {
          // 循环遍历设备数据
          res.result.records.forEach(device => {
            // 创建一个空数组用于存储按照 "workshop_dictText" 分组后的数据
            const groupedDevice = []
            device.equipList = res.result.records
            if (device.preSpinDevices != null) {
              device.preSpinDevices.forEach(item => {
                const workshopDictText = item.workshopDictText
                const dailyPlanId = device.id
                // 查找是否存在相应的车间分组
                let workshopGroup = groupedDevice.find(group => group.cj === workshopDictText)
                // 如果不存在则创建一个新的分组
                if (!workshopGroup) {
                  workshopGroup = {
                    cj: workshopDictText,
                    dailyPlanId: dailyPlanId,
                    devSnArea: []
                  }
                  groupedDevice.push(workshopGroup)
                }
                // 添加设备到相应的车间分组中
                workshopGroup.devSnArea.push(item)
              })
            }

            // 在这里使用groupedDevice，它包含了按照 "workshop_dictText" 分组后的数据
            device.equipList = groupedDevice
          })
          this.showList = res.result.records
          console.log('showList', this.showList)
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    close() {
      this.$emit('close')
      this.visible = false
      this.chose = []
      this.equipList = []
    },

    handleOk() {
      if (this.addTable) {
        this.$emit('planChoseSubmit', this.param, this.selectPlanData, this.chose)
      } else {
        this.$emit('editSubmit', this.param, this.selectPlanData, this.chose, this.editItem)
      }
      this.close()
    },
    handleCancel() {
      this.close()
    },
    closeTag(val, index) {
      let cj = null,
        str = null,
        arrSplit = null
      if (this.isEquipment) {
        cj = val.substring(0, 2)
        str = val.substring(3)
        arrSplit = str.split('~#')
      } else {
        str = val.substring(1)
        arrSplit = str.split('~#')
      }
      let arr = [parseInt(arrSplit[0]), parseInt(arrSplit[1])]
      let test = []
      for (let i = 0; i < arr[1] - arr[0] - 1; i++) {
        test.push(arr[0] + 1 * (i + 1))
      }
      arr.splice(1, 0, ...test)
      // 去掉相同项
      let final = []
      for (let i = 0; i < this.chose.length; i++) {
        for (let j = 0; j < arr.length; j++) {
          // 粗纱特殊情况
          const item = this.isEquipment ? cj + arr[j] : arr[j]
          if (this.chose[i].split('/')[0] == item) {
            this.chose[i] = ''
            break
          }
        }
      }
      for (let i = 0; i < this.chose.length; i++) {
        if (this.chose[i] != '') {
          final.push(this.chose[i])
        }
      }
      this.tags.splice(index, 1)
      if (this.tags.length == 0) {
        this.selectDeviceIds = []
      }
      this.chose = final
    },
    getSeiresDevsnCs(arr) {
      let chose = []
      let paramArr = this.getEquipmentScopeParam(arr)
      paramArr.map(item => {
        item.devSnArea.sort((a, b) => a.devSn - b.devSn) // 根据 devSn 属性排序
        let devStrArr = this.getSeiresDevsn(item.devSnArea)
        devStrArr = devStrArr.map(t => item.cj + t)
        chose = chose.concat(devStrArr)
      })
      return chose
    },
    getEquipmentScopeParam(arr) {
      let paramArr = []
      let deviceIds = []
      arr.map(item => {
        let cj = item.substring(0, 2)
        let devSn = item.substring(2).split('/')[0]
        let deviceId = item.substring(2).split('/')[1]
        //获取选择的设别ID列表
        deviceIds.push(deviceId)
        this.selectDeviceIds = deviceIds
        //处理数据
        let index = paramArr.findIndex(find => find.cj == cj)
        if (index > -1) {
          paramArr[index]['devSnArea'].push({
            devSn,
            deviceId
          })
        } else {
          paramArr.push({
            cj,
            devSnArea: [
              {
                devSn,
                deviceId
              }
            ]
          })
        }
        // if (index > -1) {
        //   paramArr[index]['devSnArea'].push(devSn)
        // } else {
        //   paramArr.push({
        //     cj,
        //     devSnArea: [devSn]
        //   })
        // }
      })
      return paramArr
    },
    toggleChose(val) {
      if (val) {
        console.log(val)
        const groupedResult = val
          .map(item => {
            const [first, second] = item.split('*')
            return { first: first, second: second }
          })
          .reduce((acc, obj) => {
            const key = obj.first
            if (!acc[key]) {
              acc[key] = { dailyPlanId: obj.first, deviceIds: [obj.second.toString()] }
            } else {
              acc[key].deviceIds.push(obj.second.toString())
            }
            return acc
          }, {})

        const finalResult = Object.values(groupedResult)
        this.selectPlanData = finalResult
      }
    },
    // 获取连续车台
    getSeiresDevsn(arr) {
      var result = [],
        i = 0,
        str = []
      if (arr.length > 0) {
        result[i] = [arr[0].devSn]
        arr.reduce(function(prev, cur) {
          parseInt(cur.devSn) - parseInt(prev.devSn) === 1 ? result[i].push(cur.devSn) : (result[++i] = [cur.devSn])
          return cur
        })
        result.map(item => {
          if (item.length > 1) {
            str.push(`#${item[0]}~#${item[item.length - 1]}`)
          } else {
            str.push(`#${item[0]}`)
          }
        })
      } else {
        str = []
      }
      return str
    },
    checkBtn(row) {
      console.log(row)
      // 提取startNum和endNum的值
      const startNum = parseInt(row.startNum)
      const endNum = parseInt(row.endNum)
      // 选择devSnArea中deviceNo值在[startNum, endNum]范围内的内容
      const selectedDevices = row.devSnArea.filter(device => {
        const deviceNo = parseInt(device.deviceNo)
        return deviceNo >= startNum && deviceNo <= endNum
      })
      // 打印选中的内容
      selectedDevices.forEach(device => {
        const result = row.dailyPlanId + '*' + device.id
        if (!this.chose.includes(result)) {
          // 只处理以 row.cj 开头的数据
          this.chose.push(result)
          //增加标签选择
          if (this.isEquipment) {
            this.tags = this.getSeiresDevsnCs(this.chose)
          } else {
            this.chose = this.chose.sort(function(a, b) {
              return a - b
            })
            this.tags = this.getSeiresDevsn(this.chose)
          }
        }
      })
      this.toggleChose(this.chose)
    },
    unCheckBtn(row) {
      console.log(this.chose)
      // 提取startNum和endNum的值
      const startNum = parseInt(row.startNum)
      const endNum = parseInt(row.endNum)
      // 选择devSnArea中deviceNo值在[startNum, endNum]范围内的内容
      const selectedDevices = row.devSnArea.filter(device => {
        const deviceNo = parseInt(device.deviceNo)
        return deviceNo >= startNum && deviceNo <= endNum
      })
      // 打印选中的内容
      selectedDevices.forEach(device => {
        const result = row.dailyPlanId + '*' + device.id
        if (this.chose.includes(result)) {
          this.chose = this.chose.filter(item => item !== result)
          //增加标签选择
          if (this.isEquipment) {
            this.tags = this.getSeiresDevsnCs(this.chose)
          } else {
            this.chose = this.chose.sort(function(a, b) {
              return a - b
            })
            this.tags = this.getSeiresDevsn(this.chose)
          }
        }
      })
      this.toggleChose(this.chose)
    }
  }
}
</script>

<style scoped lang="less">
.box {
  border: 1px solid #dee0e3;
  border-radius: 2px;
  overflow: auto;
  box-sizing: border-box;
  margin-top: 15px;
}

.content {
  width: 100%;
  padding: 5px 15px;

  .grid {
    display: grid;
    grid-template-columns: repeat(37, 25px);
    grid-column-gap: 8px;
    grid-row-gap: 15px;
  }

  .split {
    grid-column: span 2;
  }

  .wall {
    position: relative;

    &:after {
      display: block;
      content: '';
      position: absolute;
      left: 41px;
      top: -21px;
      width: 5px;
      height: 499px;
      background: rgba(53, 65, 86, 0.5);
      border: 1px solid #354156;
    }
  }

  .el-checkbox-button {
    width: 25px;
    height: 80px;
    border-radius: 2px;

    .el-checkbox-button__inner {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 100%;
      border: none;
      background: #f1f5f8;
      color: #4a576c;
      font-size: 16px;
      padding: 0;
      box-shadow: none;
    }

    &.is-checked {
      .el-checkbox-button__inner {
        background: #e1f0ff;
        color: #2c67f6;
      }
    }

    &.is-disabled {
      .el-checkbox-button__inner {
        background: #e3e3e3;
        color: rgba(74, 87, 108, 0.3);
      }
    }
  }
}

.mb10 {
  margin-bottom: 10px;
}

.equipment-scope {
  padding: 10px 0;
  border-bottom: 1px solid #dee0e3;

  &:last-child {
    border-bottom: none;
  }
}

.title-cj {
  color: #333;
  font-weight: bold;
  font-size: 18px;
  margin-bottom: 6px;
}
</style>
